package com.stork.sms.activity;

import java.io.IOException;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import org.json.JSONArray;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.navdrawer.SimpleSideDrawer;
import com.stork.sms.R;
import com.stork.sms.service.all.ServiceMethods;
import com.stork.sms.service.attendence.StudentAttendence;
import com.stork.sms.utilities.Constants;
import com.stork.sms.utilities.SharedPreference;

public class AttendenceActivity extends Activity {
	private int fYear;
    private int fMonth;
    private int fDay;
    private int tYear;
    private int tMonth;
    private int tDay;
    static final int FROM_DATE_DIALOG_ID = 1;
    static final int TO_DATE_DIALOG_ID = 2;
    public static final String LOGIN_ID="username";
    private SimpleSideDrawer ssdrawer;
	private static final String SOAP_ACTION = "http://tempuri.org/getstudentattendance";
	private static final String METHOD_NAME = "getstudentattendance";

private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://10.0.2.2:2341/smsservice/webmethods.asmx";
ProgressDialog progressdialog;
 
 JSONArray Items=null;
    ArrayList<HashMap<String,Integer>>Itemlist;
    
    TextView fdate,tdate,workingdays,presentdays,absentdays,halfdayabsent;
    TextView vfdate,vtdate,vwd,vpd,vad,vhday;
    Button submit,abslog;
   LinearLayout layout;
    StudentAttendence studentattendence;
    
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_attendence);
	ActionBar actionBar = getActionBar();
	actionBar.setTitle("Attendance");
	actionBar.setDisplayHomeAsUpEnabled(true);
	fdate=(TextView)findViewById(R.id.from);
	tdate=(TextView)findViewById(R.id.to);
	workingdays=(TextView)findViewById(R.id.wd);
	presentdays=(TextView)findViewById(R.id.pd);
	absentdays=(TextView)findViewById(R.id.abs);
	halfdayabsent=(TextView)findViewById(R.id.hdaya);
	vfdate=(TextView)findViewById(R.id.vfdate);
	vtdate=(TextView)findViewById(R.id.vtdate);
	vwd=(TextView)findViewById(R.id.vwdval);
	vpd=(TextView)findViewById(R.id.vpdval);
	vad=(TextView)findViewById(R.id.vabsval);
	vhday=(TextView)findViewById(R.id.vhday);
	layout=(LinearLayout)findViewById(R.id.llayout);
	layout.setVisibility(View.INVISIBLE);
	ssdrawer=new SimpleSideDrawer(this);
	ssdrawer.setRightBehindContentView(R.layout.drawer);
	abslog=(Button)findViewById(R.id.absentlog);
	submit=(Button)findViewById(R.id.submit);
	submit.setOnClickListener(new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			new StuAtt().execute();
			layout.setVisibility(View.VISIBLE);
		}
	});
	abslog.setOnClickListener(new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			String f=vfdate.getText().toString();
			String t=vtdate.getText().toString();
			Bundle b=new Bundle();
			b.putString("fdate", f);
			b.putString("tdate",t);
			Intent al=new Intent(AttendenceActivity.this,AttendanceLogActivity.class);
			al.putExtras(b);
			startActivity(al);
		}
	});
	vfdate.setOnClickListener(new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			 showDialog(FROM_DATE_DIALOG_ID);
		}
	});

    /* get the current date */
    final Calendar c = Calendar.getInstance();
    fYear = c.get(Calendar.YEAR);
    fMonth = c.get(Calendar.MONTH);
    fDay = c.get(Calendar.DAY_OF_MONTH);
    updateStartDisplay();
    vtdate.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            showDialog(TO_DATE_DIALOG_ID);
        }
    });

    /* get the current date */
    final Calendar c1 = Calendar.getInstance();
    tYear = c1.get(Calendar.YEAR);
    tMonth = c1.get(Calendar.MONTH);
    tDay = c1.get(Calendar.DAY_OF_MONTH);

    /* display the current date (this method is below)  */
    updateEndDisplay();
}
private void updateStartDisplay() {
	if(fDay<=9&&fMonth<=9){
		vfdate.setText(
	            new StringBuilder()
	                // Month is 0 based so add 1
	            
	            .append(fYear).append("/").append(0)
	                .append(fMonth + 1).append("/").append(0)
	                .append(fDay).append("")
	                );

	}
	else if(fMonth<=9&&fDay>9){
		vfdate.setText(
	            new StringBuilder()
	                // Month is 0 based so add 1
	            
	            .append(fYear).append("/").append(0)
	                .append(fMonth + 1).append("/")
	                .append(fDay).append("")
	                );

	}else if(fDay>9&&fMonth>9){
    vfdate.setText(
            new StringBuilder()
                // Month is 0 based so add 1
            
            .append(fYear).append("/")
                .append(fMonth + 1).append("/")
                .append(fDay).append("")
                );

	}
	else if(fDay<=9&&fMonth>9){
		 vfdate.setText(
		            new StringBuilder()
		                // Month is 0 based so add 1
		            
		            .append(fYear).append("/")
		                .append(fMonth + 1).append("/").append(0)
		                .append(fDay).append("")
		                );

	}
}


private void updateEndDisplay() {
	if(tDay<=9&&tMonth<=9){
		vtdate.setText(
	            new StringBuilder()
	                // Month is 0 based so add 1
	                
	                
	                .append(tYear).append("/").append(0)
	                .append(tMonth + 1).append("/").append(0)
	                .append(tDay).append(""));
	}else if(tDay>9&&tMonth<=9){
		vtdate.setText(
	            new StringBuilder()
	                // Month is 0 based so add 1
	                
	                
	                .append(tYear).append("/").append(0)
	                .append(tMonth + 1).append("/")
	                .append(tDay).append(""));
	}else if(tDay>9&&tMonth>9) {
    vtdate.setText(
            new StringBuilder()
                // Month is 0 based so add 1
                
                
                .append(tYear).append("/")
                .append(tMonth + 1).append("/")
                .append(tDay).append(""));
	}
	else if(tDay<=9&&tMonth>9){
		vtdate.setText(
	            new StringBuilder()
	                // Month is 0 based so add 1
	                
	                
	                .append(tYear).append("/")
	                .append(tMonth + 1).append("/").append(0)
	                .append(tDay).append(""));
			
	}
}
/* the callback received when the user "sets" the date in the dialog for the start date function */

private DatePickerDialog.OnDateSetListener mDateSetListener =
           new DatePickerDialog.OnDateSetListener() {

           public void onDateSet(DatePicker view, int year, 
                                 int monthOfYear, int dayOfMonth) {
               fYear = year;
               fMonth = monthOfYear;
               fDay = dayOfMonth;
               updateStartDisplay();
           }
       };

/* the callback received when the user "sets" the date in the dialog for the end date function  */

private DatePickerDialog.OnDateSetListener endDateSetListener =
       new DatePickerDialog.OnDateSetListener() {

           public void onDateSet(DatePicker view, int year, 
                                 int monthOfYear, int dayOfMonth) {
               tYear = year;
               tMonth = monthOfYear;
               tDay = dayOfMonth;
               updateEndDisplay();
           }
       };

protected Dialog onCreateDialog(int id) {
   switch (id) {
   case TO_DATE_DIALOG_ID:
       return new DatePickerDialog(this,
                   endDateSetListener,
                   tYear, tMonth, tDay);
       
   case FROM_DATE_DIALOG_ID:
       return new DatePickerDialog(this,
                   mDateSetListener,
                   fYear, fMonth, fDay);
   }
   return null;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
	// Inflate the menu; this adds items to the action bar if it is present.
	getMenuInflater().inflate(R.menu.main, menu);
	return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
      switch (item.getItemId()) {
         // Respond to the action bar's Up/Home button
         case android.R.id.home:
        	 super.onBackPressed();
         return true;
         case R.id.action_settings:
 			ssdrawer.toggleRightDrawer();
 			return true;
 		
      }
      return super.onOptionsItemSelected(item);
   }

private class StuAtt extends AsyncTask<String, String,StudentAttendence>
{	Constants con;
	Toast toast = Toast.makeText(getApplicationContext(), "",
            Toast.LENGTH_SHORT);
	
@Override
protected void onPreExecute() {
	// TODO Auto-generated method stub
	super.onPreExecute();
	progressdialog=new ProgressDialog(AttendenceActivity.this);
	progressdialog.setMessage("Please Wait......");
	progressdialog.setCancelable(false);
	progressdialog.show();
}

	@Override
	protected StudentAttendence doInBackground(String... params) {
		String id=SharedPreference.readString(getApplicationContext(), LOGIN_ID, "");
		String f=vfdate.getText().toString();
		String t=vtdate.getText().toString();
		ServiceMethods sm=new ServiceMethods();
		studentattendence=sm.Attendance(id, f, t);
		return studentattendence;
	}
	protected void onPostExecute(final StudentAttendence studentAttendence) {
		// TODO Auto-generated method stub
		//super.onPostExecute(result);
		if(progressdialog.isShowing())
			progressdialog.dismiss();
		System.out.println("value in post"+studentAttendence);
		String code=studentAttendence.getCode();
		String msg=studentAttendence.getMessage();
		System.out.println("value code is"+code);
		System.out.println("value message is"+msg);
		if(code.equalsIgnoreCase(con.mSERVICEINVALID)){
			//Log.i("inside post","444 exception");
			
			AttendenceActivity.this.runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					 final AlertDialog.Builder alertBox = new AlertDialog.Builder(AttendenceActivity.this);
					// TODO Auto-generated method stub
					 String msg=studentAttendence.getMessage();
					toast.setText(msg);
					toast.show();
					toast.setText(msg);
					toast.show();
					alertBox.setTitle("Error Message");
					alertBox.setMessage(msg);
					alertBox.setCancelable(true);
					alertBox.setPositiveButton("Yes",
		                    new DialogInterface.OnClickListener() {
		                public void onClick(DialogInterface dialog, int id) {
		                    Intent A=new Intent(AttendenceActivity.this,GridHomeMenuActivity.class);
		                    startActivity(A);
		                    finish();
		                    }
		                	
		            });
					AlertDialog ad=alertBox.create();
					ad.show();	
				}
				});
		}
		else if(code.equalsIgnoreCase(con.mSERVICEFAILED)){
			Log.i("inside post","404 exception");
			
			toast.setText(msg);
			toast.show();

		}else{
		
		System.out.println("on post \t"+studentattendence.getAttendance().getWorkingdays());
		System.out.println("on post \t"+studentattendence.getAttendance().getFulldayleave());
		System.out.println("on post \t"+studentattendence.getAttendance().getHalfdayleave());
		vwd.setText(studentAttendence.getAttendance().getWorkingdays());
		vpd.setText(studentAttendence.getAttendance().getTotalpresentdate());
		vad.setText(studentAttendence.getAttendance().getFulldayleave());
		vhday.setText(studentAttendence.getAttendance().getHalfdayleave());
		}
	}
	
}
/*public void Attendance(String username,String fdate,String tdate)
{
    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

	 PropertyInfo properties=new PropertyInfo();
	PropertyInfo properties1=new PropertyInfo();
	PropertyInfo properties2=new PropertyInfo();
	properties.name="studentid";
	properties1.name="fromdate";
	properties2.name="todate";
	properties.type=PropertyInfo.STRING_CLASS;

	request.addProperty(properties,username);
	request.addProperty(properties1,fdate);
	request.addProperty(properties2,tdate);
   SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
            SoapEnvelope.VER11);
    envelope.dotNet = true;

    envelope.setOutputSoapObject(request);

    HttpTransportSE httpTransport = new HttpTransportSE(URL);
    
    httpTransport.debug=true;
    
    try
    {	Log.d("webservice", "inside the try");
    httpTransport.call(SOAP_ACTION, envelope);
    SoapPrimitive result=(SoapPrimitive) envelope.getResponse();
    Log.i("result", result.toString());
        
        System.out.println("resultAAAAAAAAAAAAAAAAAAAA"+result);
       String bracket =result.toString();
        GsonBuilder gsonBuilder=new GsonBuilder();
        Gson gson=gsonBuilder.create();
       
		 studentattendence=gson.fromJson(bracket, StudentAttendence.class);
//       
        
    }
    catch (SocketException exception)
    {
        System.out.println(exception);
    } catch (IOException e) {
		e.printStackTrace();
	} catch (XmlPullParserException e) {
		e.printStackTrace();
	}
}*/



}

